package userlimitModel

import (
	"arabApi/app/api/models"
	"arabApi/app/api/requests"
	"arabApi/app/api/requests/userlimitRequest"
	"arabApi/pkg/database"
	"arabApi/pkg/helpers"
	"github.com/spf13/cast"
)

type Menu struct {
	models.BaseModel
	MenuName string `gorm:"column:menu_name" db:"menu_name" json:"menu_name"` //  菜单名称
	PId      int64  `gorm:"column:p_id" db:"p_id" json:"p_id"`                //  父级id
	Index    string `gorm:"column:index" db:"index" json:"index"`             //  index
	Title    string `gorm:"column:title" db:"title" json:"title"`             //  标题
	Type     int64  `gorm:"column:type" db:"type" json:"type"`                //  1 菜单 2 链接
	Order    int64  `gorm:"column:order" db:"order" json:"order"`             // 排序
	models.CommonTimestampsField
}

func (Menu) TableName() string {
	return "tp_menu"
}

func MenuList(r requests.PageStruct) ([]Menu, int64) {
	var count int64
	dd := database.DB.Model(Menu{})

	var users []Menu
	p := cast.ToInt(r.Page)
	ps := cast.ToInt(r.PageSize)

	dd.Count(&count).Limit(ps).Offset((p - 1) * ps).Order("order").Find(&users)
	return users, count
}

func (Menu) MenuAdd(r userlimitRequest.MenuAdd) uint64 {
	u := &Menu{}
	if err := helpers.Copy(r, u); err != nil {
		return 0
	}
	database.DB.Create(u)
	return u.ID

}

func MenuMsg(id int64) Menu {
	var user Menu
	database.DB.Model(Menu{}).Where("id = ?", id).Find(&user)
	return user
}

func (Menu) MenuEdit(r userlimitRequest.MenuAdd) error {
	u := &Menu{}
	if err := helpers.Copy(r, u); err != nil {
		return err
	}
	res := database.DB.Where("id = ?", u.ID).Updates(u)
	return res.Error

}

func MenuList1() []map[string]interface{} {

	var result []map[string]interface{}
	//database.DB.Model(RoleMenu{}).Select("tp_menu.id,tp_menu.menu_name").
	//	Joins("inner join tp_menu on tp_role_menu.menu_id = tp_menu.id").Find(&result)
	database.DB.Debug().Model(Menu{}).Order("p_id ,`order`").Find(&result)
	return result

}

func MenuList2(r int) []map[string]interface{} {
	var result []map[string]interface{}
	//database.DB.Model(RoleMenu{}).Joins("inner join tp_menu on tp_role_menu.menu_id = tp_menu.id").
	//	Where("role_id = ? ", r).Where("tp_menup_id != 0").Find(&result)
	database.DB.Model(RoleMenu{}).Where("role_id = ? ", r).Group("menu_id").Find(&result)
	return result

}
